< previous page page_187 next page >

Page 187
In this example you may need to change both the string variable, strValue, and you may also need to return how many characters were changed by the StringChange() function. It does not really matter what the StringChange() function doesthis is just to illustrate the point that sometimes a ByRef call is necessary.
Call by Value
To ensure that a procedure does not change any of the values or parameters passed to it, use the ByVal keyword when declaring arguments. When the ByVal keyword is used, Visual Basic passes a copy of the value in the variable, not the actual address of where the variable is stored. This way, any changes you make to any of the lower-level arguments will not change the values in the calling procedure. Heres an example:
9f31265bb40b592b1929e18a47ab28e5.gif
Private Sub cmdValue_Click ()
   Dim intRet As Integer
   Dim strRet As String

   intRet = 10
   strRet = "Bill"

   Call ProcByValue(intRet, strRet)

   Me.Print intRet
   Me.Print strRet
End Sub
In the ProcByValue procedure, the keyword ByVal is placed in front of the declaration of the arguments:
9f31265bb40b592b1929e18a47ab28e5.gif
Sub ProcByValue (ByVal intArg1 As Integer, _
                 ByVal strArg2 As String)
   intArg1 = 20
   strArg2 = "Gates"
End Sub
If you execute the cmdValue_Click() event, the arguments do not change, so the values printed are 10 and Bill. This format is probably used more often than the call by reference, because most of the time you just need to pass values to another routine without changing the values. In Figure 9.4 the lines for the calling procedure and the called procedure point to different locations in memory. This is what happens when you use the ByVal keyword, the values are stored in separate memory locations.

 
< previous page page_187 next page >

If you like this book, buy it!